package org.cloud.core.common.anno.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Violet
 * @description 方法执行时间注解实现
 * @date 2021/5/22
 */
@Aspect
@Component
public class MethodTimeAspect {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(org.cloud.core.common.anno.MethodTime)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object before(ProceedingJoinPoint joinPoint) {
        long startTime = System.currentTimeMillis();
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("统计方法时间时出错", throwable);
        }
        long endTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() +"."+ signature.getName();
        log.info("执行[{}]耗时 {} 毫秒",methodName,endTime-startTime);
        return obj;
    }
}
